<?php

namespace app\api\controller;

use app\api\logic\WeChatLogic;
use app\api\server\CurlServer;
use think\facade\Config;
use think\session;

class WeChat extends ApiBase
{

    public $like_not_need_login = ['jsconfig', 'index', 'getQrcode','setMenu'];


    /**
     * 获取二维码
     */
    public function getQrcode()
    {
        $qrcode = (new WeChatLogic)->getQrcode();

        $this->_success("成功", $qrcode);
    }

    /**
     * 接收事件推送
     */
    public function index()
    {
        // $echoStr = $_GET["echostr"];

        // echo $echoStr;

        //1.获取到微信推送过来post数据（xml格式）
        // $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];//php7以上不能用
        $postStr = file_get_contents("php://input");
        // $postStr = "<xml><ToUserName><![CDATA[gh_9a04ba0fb015]]></ToUserName>\n<FromUserName><![CDATA[opkBE6-7y_e4jw9kOCXmF_3fmaLM]]></FromUserName>\n<CreateTime>1629338883</CreateTime>\n<MsgType><![CDATA[event]]></MsgType>\n<Event><![CDATA[SCAN]]></Event>\n<EventKey><![CDATA[1122]]></EventKey>\n<Ticket><![CDATA[gQFa8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyWUNQNnBpQzBkNEgxOFFadGh4MXoAAgT4vB1hAwQ8AAAA]]></Ticket>\n</xml>";
        $postArr = $this->XMLConvertMap($postStr);
        // $filename = ROOT_PATH . DS . "wxtxt" . DS . "test.txt";
        // $fp = fopen($filename, "w");
        // fwrite($fp, json_encode($postStr));
        // fclose($fp);

        //2.处理消息类型，并设置回复类型和内容
        // $postObj = simplexml_load_string($postArr);
        //判断该数据包是否是订阅的事件推送

        if (strtolower($postArr['MsgType']) == 'event') {
            if(strtolower($postArr['Event']) == strtolower(\app\common\model\WeChat::msg_event_subscribe)) (new WeChatLogic)->getWxUser($postArr['FromUserName'], $postArr['Ticket']);
            if(strtolower($postArr['Event']) == strtolower(\app\common\model\WeChat::msg_event_scan)) (new WeChatLogic)->getWxUser($postArr['FromUserName'], $postArr['Ticket']);
            if(strtolower($postArr['Event']) == 'TEMPLATESENDJOBFINISH') return '';
            // switch (strtolower($postArr['Event'])) {
            //     // 关注
            //     case \app\common\model\WeChat::msg_event_subscribe:
            //         (new WeChatLogic)->getWxUser($postArr['FromUserName'], $postArr['Ticket']);
            //         break;
            //     // 已关注过 关注
            //     case \app\common\model\WeChat::msg_event_scan:
            //         var_dump(\app\common\model\WeChat::msg_event_scan);die;
            //         (new WeChatLogic)->getWxUser($postArr['FromUserName'], $postArr['Ticket']);
            //         break;
            //     case 'TEMPLATESENDJOBFINISH':
            //         return "";
            //         break;
            // }
        }
        return xml($this->reply(["FROMUSERNAME" => $postArr['ToUserName'], "TOUSERNAME" => $postArr['FromUserName']]));
    }

    private function XMLConvertMap($xml)
    {
        if (!$xml) {
            throw new RuntimeException('xml 数据异常转换失败!!');
        }
        $map = array();
        libxml_disable_entity_loader(true);
        $map = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        // var_dump($map);
        return $map;
    }


    public function reply($postObj)
    {
        //回复用户消息(纯文本格式)
        $toUser = $postObj['TOUSERNAME'];
        $fromUser = $postObj['FROMUSERNAME'];
        $time = time();
        $msgType = 'text';
        $content = "感谢 \n";
        $content .= "欢迎关注'迈货网'微信公众账号";
        $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
        return $info;
    }

    public function pushMessage()
    {
        $open_id = $this->request->post("open_id");
        WeChatLogic::pushMessage($open_id);

    }

    /**
     * showdoc
     * @catalog 接口列表/微信
     * @title 微信JSSDK授权接口
     * @description
     * @method get
     * @url we_chat/jsconfig
     * @return {"code":1,"msg":"获取成功","data":{"config":{"debug":true,"beta":false,"jsApiList":["onMenuShareTimeline","onMenuShareWeibo","openLocation","getLocation","chooseWXPay","updateTimelineShareData"],"appId":"wx9d4……","nonceStr":"Ge8wD……","timestamp":1592707100,"url":"http:\/\/dragon.yixiang……","signature":"8421cfbc……"}}}
     * @param url 必填 varchar 前端当前url
     * @return_param appId string appid,公众号的唯一标识
     * @return_param timestamp int 生成签名的时间戳
     * @return_param nonceStr string 生成签名的随机串
     * @return_param signature string 签名
     * @return_param jsApiList array 需要使用的JS接口列表
     * @remark allow_share: 传入1时,则返回允许分享到朋友圈的配置
     * @number 0
     */
    public function jsConfig()
    {
        $url = $this->request->get('url');
        $result = WeChatLogic::jsConfig($url);
        if ($result['code'] != 1) {
//            $this->_error('', ['config' => $result['data']]);
            $this->_error($result['msg']);
        }
        $this->_success('', ['confsnsapi_userinfoig' => $result['data']]);
    }

    /**
     * 设置菜单
     */
    public function setMenu()
    {
        $res = (new WeChatLogic)->setMenu();
        if(!$res){
            $this->_error("失败");
        }
        $this->_success("成功");
    }
}